package com.boxing.servlet;

import com.boxing.beans.Result;
import com.boxing.beans.User;
import com.boxing.beans.UserInfo;
import com.boxing.beans.UserInfoT;
import com.boxing.service.UserService;
import com.boxing.utils.Contants;
import com.boxing.utils.Utils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet(name = "UserInfoServlet", urlPatterns = "/servlet/*")
//必须设置MultipartConfig 注解,还可以自定义文件大小等
@MultipartConfig
public class UserInfoServlet extends BaseServlet{
    private  UserService userService = new UserService();
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        byte[] bytes = req.getInputStream().readAllBytes();
        String params = new String(bytes, "utf-8");
        // 对参数进行解析
        Gson gson = new Gson();
        User user = gson.fromJson(params, User.class);
        // 去数据库里验证用户名密码是否合法 jdbc sql
        Result result = userService.login(user);
        if (result.getCode() == 200){
            // 允许登录  跳转到首页
            // 服务器端生成cookie
            String value = UUID.randomUUID().toString();
            Cookie token = new Cookie(Contants.COOKIE_TOKEN, value);
            token.setHttpOnly(true);
            token.setPath("/");
            // 设置token的有效期，浏览器会从获取到token时开始计算，时间就是参数，单位秒
            token.setMaxAge(5*60*60);

            // 第一种方式 使用 servletContext 存储token
//            servletContext.setAttribute(value, "zhangsan");

            // 第二种方式 使用session 存储 token
            HttpSession session = req.getSession(true);
            session.setAttribute(value, user.getEmail());
            // 设置session有效时间间隔
            session.setMaxInactiveInterval(5*60*60);
            resp.addCookie(token);
        }
        resp.getWriter().print(gson.toJson(result));
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解析 json 格式的数据
        ServletInputStream inputStream = req.getInputStream();
        byte[] bytes = inputStream.readAllBytes();
        String str = new String(bytes, "utf-8");
        System.out.println("服务器收到请求体中的数据："+str);
        // 解析 json 使用 gson 库解析json
        Gson gson = new Gson();
        UserInfo userInfo = gson.fromJson(str, UserInfo.class);
        System.out.println("服务器收到请求体中的数据:" + userInfo);
        // TODO 对用户名长度的检验
        Result result = userService.register(userInfo);
        String outStr = gson.toJson(result);
        resp.getWriter().print(outStr);
    }

    public void setIcon(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        // 接收客户端上传的图片
        System.out.println("接收浏览器的上传的文件");
        Part partFile = req.getPart("fileName");
        String fileName = partFile.getSubmittedFileName();
        System.out.println("fileName:"+fileName);

        // 将字节数组存储到服务器中
        File file = new File("D:\\project\\webDemo\\web\\img", fileName);
        System.out.println(file.getAbsolutePath());
        partFile.write(file.getAbsolutePath());

        String userEmail = Utils.getUserEmailFromSession(req);
        UserInfoT userInfoT = new UserInfoT();
        userInfoT.setEmail(userEmail);
        userInfoT.setIcon("/img/"+fileName);
        Result<String> result = userService.setIcon(userInfoT);
        result.setData(Utils.getServerUrl(req) + userInfoT.getIcon());
        resp.getWriter().print(gson.toJson(result));
    }

    /**
     * 获取个人信息
     */
    public void getUser(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        String userEmail = Utils.getUserEmailFromSession(req);
        Result<UserInfoT> result = userService.getUser(userEmail);
        result.getData().setIcon(Utils.getServerUrl(req) + result.getData().getIcon());
        resp.getWriter().print(gson.toJson(result));
    }
}
